package coreBiz

import (
	"reflect"

	"github.com/goccy/go-json"
)

func StructToMap(obj any) (map[string]any, error) {
	data := make(map[string]interface{})
	j, _ := json.Marshal(obj)
	err := json.Unmarshal(j, &data)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func MapStruct(obj any, data any) error {
	j, _ := json.Marshal(obj)
	err := json.Unmarshal(j, &data)
	if err != nil {
		return err
	}
	return nil
}

func StructToArgs(s any) []any {
	val := reflect.ValueOf(s)
	if val.Kind() == reflect.Ptr {
		val = val.Elem()
	}

	typ := val.Type()
	args := make([]interface{}, 0, typ.NumField()*2)

	for i := 0; i < typ.NumField(); i++ {
		field := typ.Field(i)
		value := val.Field(i)
		tag := field.Tag.Get("redis")
		if tag == "" {
			tag = field.Name
		}
		args = append(args, tag, value.Interface())
	}
	return args
}

// MapToArgs 将map转化成args
func MapToArgs(m map[string]any) []any {
	args := make([]any, 0, len(m)*2+1)
	for field, value := range m {
		args = append(args, field, value)
	}
	return args
}
